package com.anlu.base.pattern;
import io.micrometer.common.util.StringUtils;

import java.util.regex.*;
public class Valid {


    /**
     * \ : * ? " < > |
     * @param args
     */

        public static void main(String[] args) throws Exception {
            String check = "[\\\\:*?\"<>|\\t\\r\\n\\f\\e]";

//            String filename = "my/file:name?.txt";

//            String filename = "%09.docx";
            String filename = "/    .docx";

            filename = normPath(filename);
            System.out.println(filename);

            if (filename.matches(".*" + check + ".*")) {
                System.out.println("文件名包含非法字符！");
            } else {
                System.out.println("文件名合法。");
            }

            boolean isValid = inValidFilePath(filename);
            System.out.println(isValid);
    }


    public static String normPath(String path){
        if("/".equals(path)){
            return path;
        }
        if(!path.startsWith("/")){
            path = "/"+path;
        }
        if(path.indexOf("//")!=-1){
            path = path.replaceAll("//", "/");
        }
        if(path.indexOf("//")!=-1){
            path = normPath(path);
        }
        if(path.endsWith("/")){
            path = path.substring(0,path.length()-1);
        }
        if(StringUtils.isBlank(path)){
            path = "/";
        }
        return path;
    }

    public static boolean inValidFilePath(String path) throws Exception {
        //这行是含有禁止表情符号的正则，目前支持，所以去掉
        String pattern = "/\\.{1,}/|[^\\u0000-\\uFFFF]";

        //这行是去掉禁止表情符号的正则
//		String pattern = "/\\.{1,}/";

        Pattern regex1 = Pattern.compile(pattern);
        Matcher matcher = regex1.matcher(path);
        boolean inValid = matcher.find();
        if (inValid) {
            throw new Exception("invalid filename");
        } else {
            String check = "[\\\\:*?\"<>|\\t\\r\\n\\f\\e]";
            Pattern regex = Pattern.compile(check);
            matcher = regex.matcher(path);
            System.out.println("结果是:"+matcher.find());
            return matcher.find();
        }
    }
}
